#include <os/binsem.h>
#include <os/lock.h>

mutex_lock_t binsems[BINSEMS];

void init_binsems()
{
    for (int i = 0; i < BINSEMS; ++i) {
        do_mutex_lock_init(&binsems[i]);
    }
}

static int binsem_hash(uint64_t x)
{
    // a simple hash function
    x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ul;
    x = (x ^ (x >> 27)) * 0x94d049bb133111ebul;
    x = x ^ (x >> 31);
    return x % BINSEMS;
}

int get_binsem(int key){
    return binsem_hash(key);
}

int op_binsem(int binsem_id, int op){
    if(op == BINSEM_OP_LOCK)
        do_mutex_lock_acquire(&(binsems[binsem_id]));
    else if(op == BINSEM_OP_UNLOCK)
        do_mutex_lock_release(&(binsems[binsem_id]));
    else
        return 0;
    return 1;
}